#include <stdio.h>
#include <stdlib.h>

//创建了一个结构体
typedef struct std
{
    int data;
    struct std *next;
}std;

std * linked_init()
{
    std * s1 = (std *)malloc(sizeof(std));

    if (NULL == s1)
    {
        perror("malloc failed");
        return NULL;
    }

    s1->data = 10;
    s1->next = NULL;

    return s1;
}

void list_add(std *list, std data)
{
    // 安全判定
    if (NULL == list)
    {
        perror("传入链表为空");
        return;
    }
    
    // 遍历到链表尾部
    std *current = list;
    while (current->next != NULL)
    {
        current = current->next;
    }
    
    // 创建新节点并插入到链表尾部
    std *new_std = (std *)malloc(sizeof(std));
    if (NULL == new_std)
    {
        perror("malloc failed");
        return;
    }
    *new_std = data;
    new_std->next = NULL;
    current->next = new_std;
}


int main(int argc, char const *argv[])
{
    std *list = linked_init();

    // 插入数据
    std data = {.data = 20, .next = NULL};
    std data1 = {.data = 30, .next = NULL};
    list_add(list, data);
    list_add(list, data1);

    // 数据打印
    std *print_ptr = list;
    while (print_ptr != NULL)
    {
        printf("data = %d\n", print_ptr->data);
        print_ptr = print_ptr->next;
    }

    // 释放空间
    std *current = list;
    while (current != NULL)
    {
        std *temp = current;
        current = current->next;
        free(temp);
    }
    list = NULL;

    return 0;
}